package com.app.brilliant.game.controller;

import com.app.brilliant.common.api.ApiResult;
import com.app.brilliant.common.controller.BaseController;
import com.app.brilliant.common.enums.StateEnum;
import com.app.brilliant.game.response.WechatQrCodeResponse;
import com.app.brilliant.game.response.WechatQrStatusResponse;
import com.app.brilliant.game.service.WechatQrCodeService;
import com.app.brilliant.shiro.util.LoginUtil;
import com.app.brilliant.sys.bean.DevUser;
import com.app.brilliant.sys.service.DevUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 微信控制器
 */
@Slf4j
@RestController
@RequestMapping("/dev/wechat")
@Api(tags = "微信相关接口")
public class WechatController extends BaseController {

    @Autowired
    private WechatQrCodeService wechatQrCodeService;
    @Autowired
    private DevUserService devUserService;

    private boolean checkUnLogin(){
        Long devId = LoginUtil.getLoginDevUserRedisVoId();
        if(devId == null){
            return true;
        }
        DevUser sysUser = devUserService.getById(devId);
        if(sysUser == null){
            return true;
        }
        return sysUser.getState().intValue() == StateEnum.DISABLE.getCode();
    }

    @PostMapping("/qr/generate")
    @ApiOperation(value = "生成微信二维码", notes = "生成微信网页授权二维码，返回base64格式的二维码图片")
    public ApiResult<WechatQrCodeResponse> generateQrCode() {
        try {
            WechatQrCodeResponse response = wechatQrCodeService.generateQrCode();
            return ApiResult.ok(response);
        } catch (Exception e) {
            log.error("生成微信二维码失败", e);
            return ApiResult.fail("生成二维码失败：" + e.getMessage());
        }
    }

    @PostMapping("/qr/bind")
    @ApiOperation(value = "生成绑定微信二维码", notes = "生成带有token参数的微信二维码，用于账号绑定，返回base64格式的二维码图片")
    public ApiResult<WechatQrCodeResponse> generateBindQrCode() {
        try {
            if(checkUnLogin()){
                return ApiResult.fail("获取二维码失败，用户未登录");
            }
            long devId = LoginUtil.getLoginDevUserRedisVoId();
            DevUser devUser = devUserService.getById(devId);
            if(devUser.getOpenId() != null){
                return ApiResult.fail("获取二维码失败，用户已绑定微信");
            }
            WechatQrCodeResponse response = wechatQrCodeService.generateBindQrCode(devId);
            return ApiResult.ok(response);
        } catch (Exception e) {
            log.error("生成绑定微信二维码失败", e);
            return ApiResult.fail("生成绑定二维码失败：" + e.getMessage());
        }
    }

    @GetMapping("/qr/status/{qrCodeId}")
    @ApiOperation(value = "检查二维码状态", notes = "检查微信二维码的登录状态")
    public ApiResult<WechatQrStatusResponse> checkQrStatus(
            @ApiParam(value = "二维码ID", required = true) @PathVariable String qrCodeId) {
        try {
            WechatQrStatusResponse response = wechatQrCodeService.checkQrStatus(qrCodeId);
            return ApiResult.ok(response);
        } catch (Exception e) {
            log.error("检查二维码状态失败，qrId: {}", qrCodeId, e);
            return ApiResult.fail("检查状态失败：" + e.getMessage());
        }
    }

    @GetMapping("/qr/checkBindQrcodeStatus/{qrCodeId}")
    @ApiOperation(value = "检查二维码状态", notes = "检查微信二维码的登录状态")
    public ApiResult<WechatQrStatusResponse> checkBindQrcodeStatus(
            @ApiParam(value = "二维码ID", required = true) @PathVariable String qrCodeId) {
        try {
            WechatQrStatusResponse response = wechatQrCodeService.checkQrStatus(qrCodeId);
            return ApiResult.ok(response);
        } catch (Exception e) {
            log.error("检查二维码状态失败，qrId: {}", qrCodeId, e);
            return ApiResult.fail("检查状态失败：" + e.getMessage());
        }
    }

    @GetMapping("/callback")
    @ApiOperation(value = "微信回调", notes = "处理微信网页授权回调")
    public void handleCallback(
            @ApiParam(value = "微信授权码") @RequestParam(required = false) String code,
            @ApiParam(value = "状态参数") @RequestParam(required = false) String state,
            HttpServletResponse response) {
        try {
            log.info("收到微信回调，code: {}, state: {}", code, state);

            // 处理回调
            wechatQrCodeService.handleCallback(code, state);

            // 返回成功页面
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(
                    "<!DOCTYPE html><html><head><title>登录成功</title></head><body><h1>登录成功！</h1><p>请关闭此页面并返回应用。</p></body></html>");

        } catch (Exception e) {
            log.error("处理微信回调失败", e);
            try {
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().write(
                        "<!DOCTYPE html><html><head><title>登录失败</title></head><body><h1>登录失败！</h1><p>请重试。</p></body></html>");
            } catch (IOException ex) {
                log.error("返回错误页面失败", ex);
            }
        }
    }
}